import { Service } from 'egg';
import { Position } from '../model/Position';
import { Employee } from '../model/Employee';

export default class PositionService extends Service {
    /**
     * 创建职位
     * @param param 
     */
    public async createPosition(param: any) {
        try {
            param.position_name = this.ctx.helper.trim(param.position_name);
            const checkResult = await this.ctx.model.Position.findOne<Position>({ attributes: ['position_id'], where: { position_name: param.position_name, is_delete: '0' } });
            if (checkResult) {
                throw new Error(JSON.stringify({ code: 2, msg: '该职位名称已存在，不能重复添加' }));
            }
            const submitData: any = {};
            //生成主键id
            submitData.position_id = this.ctx.helper.genUUID();
            submitData.position_name = param.position_name;
            submitData.position_is_evaluate = param.position_is_evaluate;
            submitData.position_remark = param.position_remark;
            submitData.created_by = param.admin_id;
            submitData.is_delete = '0';
            const result: any = await this.ctx.model.Position.create(submitData);
            if (!result) {
                throw new Error(JSON.stringify({ code: 2, msg: '创建失败' }));
            }
        } catch (e) {
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 删除职位
     * @param param 
     */
    public async deletePosition(param: any) {
        try {
            const position_id = param.position_id;
            const searchEmployeeParam = { position_id };
            const employee = await this.searchEmployeeByPosition(searchEmployeeParam);
            if (employee.length > 0) {
                throw new Error(JSON.stringify({ code: 2, msg: '该职位存在职员不能删除，如想删除，请先到职员管理，解绑或者删除相关职员' }));
            }
            const admin_id = param.admin_id;
            const deleteResult = await this.ctx.model.Position.update({ updated_by: admin_id, is_delete: '1' }, { where: { position_id } });
            if (deleteResult[0] <= 0) {
                throw new Error(JSON.stringify({ code: 2, msg: '删除失败' }));
            }
        } catch (e) {
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 查找职位
     * @param param 
     */
    public async searchPosition() {
        try {
            const result: any = await this.ctx.model.Position.findAll<Position>({
                attributes: ['position_id', 'position_name', 'position_is_evaluate', 'position_remark'],
                where: { is_delete: '0' },
                order: [['created_at', 'DESC']]
            });
            if (result.length <= 0) {
                throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }));
            }
            return result;
        } catch (e) {
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 根据职位id查找职位信息
     * @param param 
     */
    public async searchPositionById(param: any) {
        try {
            const position_id = param.position_id;
            const result: any = await this.ctx.model.Position.findOne<Position>({ attributes: ['position_id', 'position_name', 'position_is_evaluate', 'position_remark'], where: { position_id, is_delete: '0' } });
            if (!result) {
                throw new Error(JSON.stringify({ code: 2, msg: '找不到这个职位' }));
            }
            return result;
        } catch (e) {
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 修改职位
     * @param param 
     */
    public async updatePosition(param: any) {
        try {
            param.position_name = this.ctx.helper.trim(param.position_name);
            const queryStr = `select position_id from t_position where position_name=:position_name and is_delete='0' and position_id not in (:position_id)`;
            const checkIsRepeatResult = await this.ctx.model.query(queryStr, {
                type: this.ctx.model.QueryTypes.SELECT,
                replacements: { position_name: param.position_name, position_id: param.position_id }
            });
            if (checkIsRepeatResult.length > 0) {
                throw new Error(JSON.stringify({ code: 2, msg: '该职位名称已存在，修改失败' }));
            }
            const admin_id = param.admin_id;
            const position_id = param.position_id;
            const position_name = param.position_name;
            const position_is_evaluate = param.position_is_evaluate;
            const position_remark = param.position_remark;
            const updateResult: any = await this.ctx.model.Position.update({ position_name, position_is_evaluate, position_remark, updated_by: admin_id }, { where: { position_id } });
            if (updateResult[0] <= 0) {
                throw new Error(JSON.stringify({ code: 2, msg: '修改失败' }));
            }
        } catch (e) {
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 根据职位找职员
     * @param param 
     */
    public async searchEmployeeByPosition(param: any) {
        try {
            const position_id = param.position_id;
            const result: any = await this.ctx.model.Employee.findAll<Employee>({ attributes: ['employee_id'], where: { position_id, is_delete: '0' } });
            return result;
        } catch (e) {
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }
}